import { fileURLToPath, URL } from 'node:url';
import { exec } from 'child_process';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import vueDevTools from 'vite-plugin-vue-devtools';
import UnoCSS from '@unocss/vite';
import Icons from 'unplugin-icons/vite';
import IconsResolver from 'unplugin-icons/resolver';
import Components from 'unplugin-vue-components/vite';
import { lazyImport, VxeResolver } from 'vite-plugin-lazy-import';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    vueDevTools(),
    UnoCSS(),
    Icons({
      autoInstall: true,
      scale: 1,
      defaultClass: 'inline-block',
      compiler: 'vue3',
      defaultStyle: 'width: 2em; height: 2em;',
    }),
    Components({
      resolvers: [IconsResolver({ prefix: 'iconify' })],
    }),
    lazyImport({
      resolvers: [
        VxeResolver({
          libraryName: 'vxe-table',
        }),
      ],
    }),
    {
      name: 'format-on-hmr',
      handleHotUpdate(ctx) {
        console.log(`文件 ${ctx.file} 已更新，正在执行代码检测和格式化...`);
        exec('pnpm run lint', (error, stdout, stderr) => {
          if (error) {
            console.error(`检测失败: ${error.message}`);
            return;
          }
          if (stderr) {
            console.error(`检测错误: ${stderr}`);
            return;
          }
          console.log(`检测成功: ${stdout}`);
        });

        exec('pnpm run format', (error, stdout, stderr) => {
          if (error) {
            console.error(`格式化失败: ${error.message}`);
            return;
          }
          if (stderr) {
            console.error(`格式化错误: ${stderr}`);
            return;
          }
          console.log(`格式化成功: ${stdout}`);
        });
      },
    },
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  server: {
    port: 3000,
    host: '0.0.0.0',
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:8900',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
});
